<script setup>
import { ref, computed, watch } from 'vue'
import { Head, useForm, router } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { Switch } from '@headlessui/vue'
import { 
    ArrowLeftIcon,
    EyeIcon,
    CheckCircleIcon,
    ExclamationCircleIcon,
    ArrowPathIcon
} from '@heroicons/vue/24/outline'
import { useToast } from '@/Composables/useToast'

const props = defineProps({
    post: {
        type: Object,
        required: true
    },
    categories: {
        type: Array,
        required: true
    },
    tags: {
        type: Array,
        default: () => []
    }
})

const toast = useToast()

const form = useForm({
    title: props.post.title,
    slug: props.post.slug,
    content: props.post.content,
    excerpt: props.post.excerpt || '',
    category_id: props.post.category?.id || '',
    status: props.post.published_at ? 'published' : 'draft',
    scheduled_publish_at: null,
    featured_image: null,
    tags: props.post.tags?.map(tag => tag.id) || []
})

const isPublished = ref(!!props.post.published_at)

// 编辑器配置
const editorOptions = {
    theme: 'snow',
    modules: {
        toolbar: {
            container: [
                ['bold', 'italic', 'underline', 'strike'],
                ['blockquote', 'code-block'],
                [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                [{ 'indent': '-1'}, { 'indent': '+1' }],
                [{ 'align': [] }],
                ['link', 'image'],
                ['clean']
            ],
            handlers: {
                image: imageHandler
            }
        }
    },
    placeholder: '开始写作...'
}

// 图片上传处理
async function imageHandler() {
    const input = document.createElement('input')
    input.setAttribute('type', 'file')
    input.setAttribute('accept', 'image/*')
    input.click()

    input.onchange = async () => {
        const file = input.files[0]
        if (file) {
            try {
                const formData = new FormData()
                formData.append('image', file)

                const response = await fetch(route('admin.upload.image'), {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    },
                    body: formData
                })

                if (!response.ok) {
                    throw new Error('Upload failed')
                }

                const data = await response.json()
                
                // 获取编辑器实例
                const quill = document.querySelector('.ql-editor').__vue__.$parent.quill
                
                // 获取当前光标位置
                const range = quill.getSelection(true)
                
                // 在光标位置插入图片
                quill.insertEmbed(range.index, 'image', data.url)
                
                // 将光标移动到图片后面
                quill.setSelection(range.index + 1)
            } catch (error) {
                console.error('Error:', error)
                toast.error('图片上传失败，请重试')
            }
        }
    }
}

// 监听发布状态变化
watch(isPublished, (value) => {
    form.status = value ? 'published' : 'draft'
})

// 自动生成 slug
const generateSlug = (title) => {
    return title
        .toLowerCase()
        .replace(/[\s\W-]+/g, '-')
        .replace(/^-+|-+$/g, '')
}

// 监听标题变化自动生成 slug（仅在 slug 为空或与旧标题生成的 slug 相同时）
watch(() => form.title, (value) => {
    const oldSlug = generateSlug(props.post.title)
    if (value && (!form.slug || form.slug === oldSlug)) {
        form.slug = generateSlug(value)
    }
})

// 提交表单
const submit = () => {
    // 保存当前内容
    const editor = document.querySelector('.ql-editor')
    if (editor) {
        form.content = editor.innerHTML
    }
    
    form.put(route('admin.posts.update', props.post.id), {
        preserveScroll: true,
        onSuccess: () => {
            toast.success('文章更新成功！')
        },
        onError: (errors) => {
            console.error('表单错误：', errors)
            if (errors.error) {
                toast.error(errors.error)
            } else {
                toast.error('保存失败，请检查表单信息')
            }
        }
    })
}

// 返回列表
const goBack = () => {
    router.visit(route('admin.posts.index'))
}

// 预览
const preview = () => {
    window.open(route('blog.posts.show', props.post.slug), '_blank')
}

// 是否有错误
const hasErrors = computed(() => {
    return Object.keys(form.errors).length > 0
})
</script>

<template>
    <AdminLayout>
        <Head :title="`编辑文章 - ${post.title}`" />

        <div class="space-y-6">
            <!-- 页面头部 -->
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-x-4">
                    <button
                        type="button"
                        @click="goBack"
                        class="inline-flex items-center rounded-md p-2 text-gray-400 hover:text-gray-500 hover:bg-gray-100 transition-colors"
                    >
                        <ArrowLeftIcon class="h-5 w-5" />
                        <span class="sr-only">返回</span>
                    </button>
                    <div>
                        <h1 class="text-3xl font-bold text-gray-900">编辑文章</h1>
                        <p class="mt-2 text-sm text-gray-600">编辑现有的博客文章</p>
                    </div>
                </div>
                <div class="flex items-center gap-x-3">
                    <button
                        type="button"
                        @click="preview"
                        class="inline-flex items-center gap-x-2 rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-semibold text-gray-700 shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-orange-500 focus:ring-offset-2"
                    >
                        <EyeIcon class="h-5 w-5" />
                        预览
                    </button>
                    <button
                        type="button"
                        @click="submit"
                        :disabled="form.processing"
                        class="inline-flex items-center gap-x-2 rounded-md bg-orange-600 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-orange-500 focus:outline-none focus:ring-2 focus:ring-orange-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                    >
                        <ArrowPathIcon
                            v-if="form.processing"
                            class="h-5 w-5 animate-spin"
                        />
                        <CheckCircleIcon
                            v-else
                            class="h-5 w-5"
                        />
                        {{ form.processing ? '保存中...' : '保存更改' }}
                    </button>
                </div>
            </div>

            <!-- 错误提示 -->
            <div
                v-if="hasErrors"
                class="rounded-md bg-red-50 border border-red-200 p-4"
            >
                <div class="flex">
                    <div class="flex-shrink-0">
                        <ExclamationCircleIcon class="h-5 w-5 text-red-400" />
                    </div>
                    <div class="ml-3">
                        <h3 class="text-sm font-medium text-red-800">表单验证失败</h3>
                        <div class="mt-2 text-sm text-red-700">
                            <ul class="list-disc list-inside space-y-1">
                                <li v-for="(error, field) in form.errors" :key="field">
                                    {{ error }}
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 表单内容 -->
            <form @submit.prevent="submit" class="space-y-8">
                <!-- 基本信息 -->
                <div class="bg-white rounded-lg border border-gray-200 shadow-sm">
                    <div class="px-6 py-4 border-b border-gray-200">
                        <h2 class="text-lg font-semibold text-gray-900">基本信息</h2>
                        <p class="mt-1 text-sm text-gray-600">填写文章的基本信息</p>
                    </div>
                    <div class="p-6 space-y-6">
                        <!-- 标题 -->
                        <div>
                            <label for="title" class="block text-sm font-medium text-gray-900 mb-2">
                                标题 <span class="text-red-500">*</span>
                            </label>
                            <input
                                v-model="form.title"
                                type="text"
                                id="title"
                                class="block w-full rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-900 placeholder:text-gray-400 focus:border-orange-500 focus:outline-none focus:ring-1 focus:ring-orange-500"
                                :class="{ 'border-red-300 focus:border-red-500 focus:ring-red-500': form.errors.title }"
                                placeholder="输入文章标题..."
                            >
                            <p v-if="form.errors.title" class="mt-2 text-sm text-red-600 flex items-center gap-x-1">
                                <ExclamationCircleIcon class="h-4 w-4" />
                                {{ form.errors.title }}
                            </p>
                        </div>

                        <!-- Slug -->
                        <div>
                            <label for="slug" class="block text-sm font-medium text-gray-900 mb-2">
                                别名
                                <span class="text-gray-500 text-xs font-normal ml-1">(URL 友好的标识符，留空将自动生成)</span>
                            </label>
                            <div class="flex rounded-md shadow-sm">
                                <span class="inline-flex items-center rounded-l-md border border-r-0 border-gray-300 bg-gray-50 px-3 text-sm text-gray-500">
                                    /posts/
                                </span>
                                <input
                                    v-model="form.slug"
                                    type="text"
                                    id="slug"
                                    class="block flex-1 rounded-none rounded-r-md border border-gray-300 px-3 py-2 text-sm text-gray-900 placeholder:text-gray-400 focus:border-orange-500 focus:outline-none focus:ring-1 focus:ring-orange-500"
                                    :class="{ 'border-red-300 focus:border-red-500 focus:ring-red-500': form.errors.slug }"
                                    placeholder="article-slug"
                                >
                            </div>
                            <p v-if="form.errors.slug" class="mt-2 text-sm text-red-600 flex items-center gap-x-1">
                                <ExclamationCircleIcon class="h-4 w-4" />
                                {{ form.errors.slug }}
                            </p>
                        </div>

                        <!-- 分类 -->
                        <div>
                            <label for="category_id" class="block text-sm font-medium text-gray-900 mb-2">
                                分类
                                <span class="text-gray-500 text-xs font-normal ml-1">(可选)</span>
                            </label>
                            <select
                                v-model="form.category_id"
                                id="category_id"
                                class="block w-full rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-900 focus:border-orange-500 focus:outline-none focus:ring-1 focus:ring-orange-500"
                                :class="{ 'border-red-300 focus:border-red-500 focus:ring-red-500': form.errors.category_id }"
                            >
                                <option value="">选择分类</option>
                                <option v-for="category in categories" :key="category.id" :value="category.id">
                                    {{ category.name }}
                                </option>
                            </select>
                            <p v-if="form.errors.category_id" class="mt-2 text-sm text-red-600 flex items-center gap-x-1">
                                <ExclamationCircleIcon class="h-4 w-4" />
                                {{ form.errors.category_id }}
                            </p>
                        </div>

                        <!-- 摘要 -->
                        <div>
                            <label for="excerpt" class="block text-sm font-medium text-gray-900 mb-2">
                                摘要
                                <span class="text-gray-500 text-xs font-normal ml-1">(可选，不填将自动生成)</span>
                            </label>
                            <textarea
                                v-model="form.excerpt"
                                id="excerpt"
                                rows="3"
                                class="block w-full rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-900 placeholder:text-gray-400 focus:border-orange-500 focus:outline-none focus:ring-1 focus:ring-orange-500 resize-none"
                                :class="{ 'border-red-300 focus:border-red-500 focus:ring-red-500': form.errors.excerpt }"
                                placeholder="为文章添加一个简短的摘要描述..."
                            />
                            <p v-if="form.errors.excerpt" class="mt-2 text-sm text-red-600 flex items-center gap-x-1">
                                <ExclamationCircleIcon class="h-4 w-4" />
                                {{ form.errors.excerpt }}
                            </p>
                            <p class="mt-2 text-xs text-gray-500">
                                摘要将显示在文章列表和文章详情页，帮助读者快速了解文章内容。
                            </p>
                        </div>
                    </div>
                </div>

                <!-- 内容编辑器 -->
                <div class="bg-white rounded-lg border border-gray-200 shadow-sm">
                    <div class="px-6 py-4 border-b border-gray-200">
                        <h2 class="text-lg font-semibold text-gray-900">文章内容</h2>
                        <p class="mt-1 text-sm text-gray-600">使用富文本编辑器编写文章内容</p>
                    </div>
                    <div class="p-6">
                        <div :class="{ 'has-error': form.errors.content }">
                            <QuillEditor
                                v-model:content="form.content"
                                contentType="html"
                                :options="editorOptions"
                                theme="snow"
                            />
                        </div>
                        <p v-if="form.errors.content" class="mt-2 text-sm text-red-600 flex items-center gap-x-1">
                            <ExclamationCircleIcon class="h-4 w-4" />
                            {{ form.errors.content }}
                        </p>
                    </div>
                </div>

                <!-- 发布设置 -->
                <div class="bg-white rounded-lg border border-gray-200 shadow-sm">
                    <div class="px-6 py-4 border-b border-gray-200">
                        <h2 class="text-lg font-semibold text-gray-900">发布设置</h2>
                        <p class="mt-1 text-sm text-gray-600">选择文章的发布状态</p>
                    </div>
                    <div class="p-6">
                        <div class="flex items-center gap-x-3">
                            <Switch
                                v-model="isPublished"
                                :class="[
                                    isPublished ? 'bg-orange-600' : 'bg-gray-200',
                                    'relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-orange-500 focus:ring-offset-2'
                                ]"
                            >
                                <span class="sr-only">立即发布</span>
                                <span
                                    :class="[
                                        isPublished ? 'translate-x-5' : 'translate-x-0',
                                        'pointer-events-none relative inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out'
                                    ]"
                                />
                            </Switch>
                            <div class="flex-1">
                                <span class="text-sm font-medium text-gray-900">
                                    {{ isPublished ? '立即发布' : '保存为草稿' }}
                                </span>
                                <p class="text-xs text-gray-500 mt-0.5">
                                    {{ isPublished ? '文章将立即发布到前台' : '文章将保存为草稿，不会在前台显示' }}
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </AdminLayout>
</template>

<style scoped>
.ql-editor {
    min-height: 400px;
}

.ql-toolbar.ql-snow,
.ql-container.ql-snow {
    @apply border-gray-300;
}

.ql-toolbar.ql-snow {
    @apply rounded-t-lg border border-gray-300 !important;
}

.ql-container.ql-snow {
    @apply rounded-b-lg border border-gray-300 !important;
}

.has-error .ql-toolbar.ql-snow,
.has-error .ql-container.ql-snow {
    @apply border-red-300 !important;
}

/* 图片样式 */
.ql-editor img {
    max-width: 100%;
    height: auto;
    display: block;
    margin: 1em 0;
    border-radius: 0.5rem;
}
</style>
